package com.starbaba.module.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.module.model.ApiModelItem;
import com.starbaba.module.model.ApiModelItemArray;
import com.starbaba.module.model.LoanApiModel;
import com.starbaba.module.service.ApiModuleService;
import com.starbaba.tools.sequence.Sequence;

@SuppressWarnings("rawtypes")
public class APIModuleAction extends BaseAction implements ModelDriven {
	
	private static final long serialVersionUID = 1L;
	
	private BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private LoanApiModel loanApiModel;
	
	@Resource(name="apiModuleServiceImpl")
	private ApiModuleService apiModuleService;
	
	public String show(){
		return "success";
	}
	
	public void querylist(){ 
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		List list = apiModuleService.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			LogService.error(e);
		}
	}
	
	public void updateContext(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		apiModuleService.updateContext(paramsMap);
		responseSuccess();
	}
	
	public String addPage(){
		return "success";
	}
	
	public void saveModule() {
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        LoanApiModel model = new LoanApiModel();
        String modelName = (String) paramsMap.get("model_name");
        String modelRemark = (String) paramsMap.get("model_remark");
        Integer modelType = Integer.valueOf((String) paramsMap.get("model_type"));
        String link = (String) paramsMap.get("link");
        model.setModel_name(modelName);
        model.setCtime(new Date());
        model.setLink(link);
        model.setModel_remark(modelRemark);
        model.setModel_type(modelType);
        model.setUptime(new Date());
        Long modelId = Sequence.getSequence();
        model.setId(modelId);
        
        String indexTxt = (String) paramsMap.get("index");
        List<ApiModelItem> propList = new ArrayList<ApiModelItem>();
        if (!StringUtils.isEmpty(indexTxt)) {
        	Integer index = Integer.parseInt(indexTxt);
        	//将同一个所属大项的每一小项归为一个小数组，再把每一个不同大项归为一个大数组
        	for (int i = 0; i < index; i++) {
        		ApiModelItem apiModelItem = new ApiModelItem();
        		String name = (String) paramsMap.get("name" + i);  //title
        		String content = (String) paramsMap.get("content" + i);  //key名称
        		String type = (String) paramsMap.get("type" + i);  
        		String parentObj = (String) paramsMap.get("parentObj"+i); //所属大项   
        		String reqInput = (String) paramsMap.get("reqInput"+i); //是否必填
        		String remark = (String) paramsMap.get("remark" + i);
        		apiModelItem.setKeyName(content);
        		apiModelItem.setModelType(type);
        		apiModelItem.setParentObj(parentObj);
        		apiModelItem.setRemark(remark);
        		apiModelItem.setReqInput(reqInput);
        		apiModelItem.setTitle(name);
        		propList.add(apiModelItem);
        	}
        	String propItemsJson = JSONUtils.toJsonString(propList).toString();
        	model.setProperties(propItemsJson);
        }
        
        /*String indexTxt = (String) paramsMap.get("index");
        Map<String,List<ApiModelItem>> map = new LinkedHashMap<String,List<ApiModelItem>>();
        if (!StringUtils.isEmpty(indexTxt)) {
        	Integer index = Integer.parseInt(indexTxt);
        	//将同一个所属大项的每一小项归为一个小数组，再把每一个不同大项归为一个大数组
        	for (int i = 0; i < index; i++) {
        		ApiModelItem apiModelItem = new ApiModelItem();
        		String name = (String) paramsMap.get("name" + i);  //title
        		String content = (String) paramsMap.get("content" + i);  //key名称
        		String type = (String) paramsMap.get("type" + i);  
        		String parentObj = (String) paramsMap.get("parentObj"+i); //所属大项   
        		String reqInput = (String) paramsMap.get("reqInput"+i); //是否必填
        		String remark = (String) paramsMap.get("remark" + i);
        		apiModelItem.setKeyName(content);
        		apiModelItem.setModelType(type);
        		apiModelItem.setParentObj(parentObj);
        		apiModelItem.setRemark(remark);
        		apiModelItem.setReqInput(reqInput);
        		apiModelItem.setTitle(name);
        		List<ApiModelItem> propList;
        		if(map.containsKey(parentObj)){
        			propList = map.get(parentObj);
        			propList.add(apiModelItem);
        		}else{
        			propList = new ArrayList<ApiModelItem>();
        			propList.add(apiModelItem);
        			map.put(parentObj, propList);
        		}
        	}
        	
        }
        List<ApiModelItemArray> propsList = new ArrayList<ApiModelItemArray>();
        Iterator<Map.Entry<String, List<ApiModelItem>>> iterator = map.entrySet().iterator();  
        while (iterator.hasNext()) {  
            Map.Entry<String, List<ApiModelItem>> entry = iterator.next();
            String parentObj = entry.getKey();
            List<ApiModelItem> itemList = entry.getValue();
            ApiModelItemArray itemArray = new ApiModelItemArray();
            itemArray.setParentObj(parentObj);
            itemArray.setItemList(itemList);
            propsList.add(itemArray);
        }  
        String propItemsJson = JSONUtils.toJsonArray(propsList).toString();
    	model.setProperties(propItemsJson);*/
        try {
            dao.add(model);
        } catch (AppException e1) {
            responseError(e1);
            e1.printStackTrace();
        }
        responseSuccess(); 
    }
	
	
	public String editPage(){
		return "success";
	}
	
	//编辑获取数据
	public void getModelData(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		Long id = Long.valueOf((String) paramsMap.get("id"));  
		try {
			LoanApiModel model = apiModuleService.getModelData(id);
			try {
				sendJsonMessage(JsonUtils.toJson(model, null, true, null, false));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (AppException e) {
			e.printStackTrace();
		}
	}
	
	public void updateModule(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		try {
			apiModuleService.updateModel(paramsMap);
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
        responseSuccess();
	}
	
	@Override
	public LoanApiModel getModel() {
		if (loanApiModel == null) {
			loanApiModel = new LoanApiModel();
        }
        return loanApiModel;
	}
	
	/**
     * 
     *
     * @Title responseSuccess
     * @Description <p>
     *              返回错误信息
     *              </p>
     *              　　　　　
     * @author zhengjunjie
     * @dateTime 2015年10月16日 下午2:26:53
     *
     */
    private void responseError(Exception error) {
        StringWriter writer = new StringWriter();
        error.printStackTrace(new PrintWriter(writer, true));
        ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
        JsonObject result = new JsonObject();
        result.add("result", resultJson.toJSON());
        try {
            sendJsonMessage(result.toString());
        } catch (Exception e) {
            LogService.error(e);
        }
    }
    
    private void responseSuccess() {
        JsonObject result = new JsonObject();
        result.add("result", new ResultJson().toJSON());
        try {
            sendJsonMessage(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
}
